package com.hoshiicloud.fileserver.service.impl;

import com.hoshiicloud.fileserver.config.ObsConfig;
import com.hoshiicloud.fileserver.model.CreateBucketRequest;
import com.hoshiicloud.fileserver.service.BucketService;
import com.hoshiicloud.fileserver.util.ObsUtil;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.AccessControlList;
import com.obs.services.model.BucketQuota;
import com.obs.services.model.BucketStorageInfo;
import com.obs.services.model.ObsBucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 华为云obs存储空间操作服务接口类实现
 * 
 * @author Mr.wu
 *
 */
@Service
@Slf4j
public class ObsBucketServiceImpl implements BucketService {

	@Override
	public boolean createBucket(CreateBucketRequest param) throws ObsException {
		try {
			ObsClient obsClient = new ObsClient(ObsConfig.accessKey, ObsConfig.secretAccessKey, param.getLocation());
			boolean exists = ObsUtil.bucketIsExists(param.getName());
			if (exists) {
				// TODO 返回已存在信息
				obsClient.close();
				return false;
			}

			ObsBucket obsBucket = new ObsBucket();
			obsBucket.setBucketName(param.getName());
			obsBucket.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
			obsBucket.setBucketStorageClass(ObsUtil.getStorageTypeEnum());
			obsBucket.setLocation(param.getLocation());
			obsClient.createBucket(obsBucket);

			BucketQuota quota = new BucketQuota(param.getQuota());
			obsClient.setBucketQuota(param.getName(), quota);
			obsClient.close();

			return true;
		} catch (ObsException e) {
			// TODO: handle exception
			throw e;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e){
			e.printStackTrace();
			log.info("系统异常:"+e.getMessage());
		}
		return false;
	}

	@Override
	public void test() throws Exception {
		// throw new Exception("异常测试");
		throw new ObsException("华为云异常测试");
	}

	@Override
	public List<ObsBucket> getBucketList() throws Exception {
		return ObsUtil.getObsBucketList();
	}

	@Override
	public boolean deleteBucket(String bucketName) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public BucketStorageInfo getBucketStorageInfo(String bucketName) {
		// TODO Auto-generated method stub
		return null;
	}

}
